/**
 * @file		delay.c
 * @brief 		waiting functions
 */

#include "../mcu/types.h"
#include "../mcu/delay.h"



void wait_1us(u_int cnt)
{
#if F_CPU == 160000000
	// 16MHz : 16 CLK 1us : 1 + (1 + (1+1)*4 + 1 + (2+1))*cnt + 1  + 1
	asm volatile
	(
		"movw	r24, %A0"		"\n\t"
		"L_US:"				"\n\t"
		"ldi	r26, lo8(4)"	 	"\n\t"
		"L_US0:"			"\n\t"
		"dec	r26"			"\n\t"
		"brne	L_US0"			"\n\t"
		"sbiw	r24, 1"			"\n\t"
		"brne	L_US"			"\n\t"
		"nop"				"\n\t"
		:  :"r" (cnt)
	);
#elif F_CPU == 14745600
	// 14.74560MHz : 15 CLK 1us : 1 + (1*11 + (2+1))*cnt + 1  + 1
	asm volatile
	(
		"movw	r24, %A0"		"\n\t"
		"L_US%=:"				"\n\t"
		"nop"				"\n\t"
		"nop"				"\n\t"
		"nop"				"\n\t"
		"nop"				"\n\t"
		"nop"				"\n\t"
		"nop"				"\n\t"
		"nop"				"\n\t"
		"nop"				"\n\t"
		"nop"				"\n\t"
		"nop"				"\n\t"
		"nop"				"\n\t"
		"sbiw	r24, 1"			"\n\t"
		"brne	L_US%="			"\n\t"
		"nop"				"\n\t"
		:  :"r" (cnt)
	);	

#elif F_CPU == 12000000
	// 12MHz : 12 CLK 1us : 1 + (1*9 + (2+1))*cnt + 1  + 1
	asm volatile
	(
		"movw	r24, %A0"		"\n\t"
		"L_US%=:"				"\n\t"
		"nop"				"\n\t"
		"nop"				"\n\t"
		"nop"				"\n\t"
		"nop"				"\n\t"
		"nop"				"\n\t"
		"nop"				"\n\t"
		"nop"				"\n\t"
		"nop"				"\n\t"
//		"nop"				"\n\t"
		"sbiw	r24, 1"			"\n\t"
		"brne	L_US%="			"\n\t"
		"nop"				"\n\t"
		:  :"r" (cnt)
	);	
#elif F_CPU == 11059200
	// 11.xMHz : 11.x CLK 1us : 1 + (1*8 + (2+1))*cnt + 1  + 1
	asm volatile
	(
		"movw	r24, %A0"		"\n\t"
		"L_US%=:"				"\n\t"
		"nop"				"\n\t"
		"nop"				"\n\t"
		"nop"				"\n\t"
		"nop"				"\n\t"
		"nop"				"\n\t"
		"nop"				"\n\t"
		"nop"				"\n\t"
		"sbiw	r24, 1"			"\n\t"
		"brne	L_US%="			"\n\t"
		"nop"				"\n\t"
		:  :"r" (cnt)
	);	
#elif F_CPU == 8000000
	// 8MHz : 8 CLK 1us : 1 + (1*5 + (2+1))*cnt + 1  + 1
	asm volatile
	(
		"movw	r24, %A0"		"\n\t"
		"L_US%=:"				"\n\t"
		"nop"				"\n\t"
		"nop"				"\n\t"
		"nop"				"\n\t"
		"nop"				"\n\t"
		"nop"				"\n\t"
		"sbiw	r24, 1"			"\n\t"
		"brne	L_US%="			"\n\t"
		"nop"				"\n\t"
		:  :"r" (cnt)
	);	
#else

	#error "delay clock undefined"

#endif
}



